package top.jacktgq.lock.reentrantLock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import top.jacktgq.utils.LogUtils;
import top.jacktgq.utils.Sleeper;
/**
 * 
 * @Title: TestReentrantLock.java 
 * @Package top.jacktgq.lock 
 * @Description: 测试ReentrantLock：条件变量
 * @author CandyWall   
 * @date 2020年11月1日 下午5:49:07 
 * @version V1.0
 */
public class Demo4_2_await_signal {
	private static ReentrantLock room = new ReentrantLock();
	//等待烟的休息室
	private static Condition waitCigaretteSet = room.newCondition();
	//等待外卖的休息室
	private static Condition waitTakeoutSet = room.newCondition();
	private static boolean hasCigarette = false;	//有没有烟
	private static boolean hasTakeout = false;		//有没有外卖
	public static void main(String[] args) {
		new Thread(() -> {
			room.lock();
			try {
				LogUtils.log("Demo4_2", "有烟没？" + hasCigarette);
				while(!hasCigarette) {
					LogUtils.log("Demo4_2", "没烟，先歇会儿！");
					try {
						waitCigaretteSet.await();
					} catch (InterruptedException e) {
						e.printStackTrace();
						return;
					}
				}
				
				LogUtils.log("Demo4_2", "可以开始干活了！");
			} finally {
				room.unlock();
			}
				
				
		}, "小南").start();
		new Thread(() -> {
			room.lock();
			try {
				LogUtils.log("Demo4_2", "外卖送到没？" + hasTakeout);
				while(!hasTakeout) {
					LogUtils.log("Demo4_2", "没送到，先歇会儿！");
					try {
						waitTakeoutSet.await();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				
				LogUtils.log("Demo4_2", "可以开始干活了！");
			} finally {
				room.unlock();
			}
		}, "小女").start();
		
		Sleeper.sleep(1);
		new Thread(() -> {
			room.lock();
			try {
				hasTakeout = true;
				LogUtils.log("Demo4_2", "外卖送到了哟！");
				waitTakeoutSet.signalAll();
			} finally {
				room.unlock();
			}
		}, "外卖小哥").start();
		new Thread(() -> {
			room.lock();
			try {
				hasCigarette = true;
				LogUtils.log("Demo4_2", "烟买来了！");
				waitCigaretteSet.signalAll();
			} finally {
				room.unlock();
			}
		}, "小弟").start();
	}	
}
